package src.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020-06-04
 */
public class NettyServer {

    public static void main(String[] args) {

        // bossGroup只是处理连接请求 默认含有子线程数：cup核数*2
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        // workerGroup负责真正的客户端业务处理
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();

            // 设置两个线程组
            bootstrap.group(bossGroup, workerGroup)
                    // 使用NioServerSocketChannel作为服务器通道实现
                    .channel(NioServerSocketChannel.class)
                    // 设置线程队列得到的连接数
                    .option(ChannelOption.SO_BACKLOG, 128)
                    // 设置保持活动连接状态
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    // 指定handler
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyServerHandler());
                        }
                    });
            System.out.println("Server is ready...");
            ChannelFuture channelFuture = bootstrap.bind(6668).sync();

            channelFuture.addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    System.out.println("监听6668端口成功。。。。");
                } else {
                    System.out.println("监听6668失败。。。。");
                }
            });

            channelFuture.channel().closeFuture().sync();


        } catch (Exception e) {

        }
    }
}
